package com.lbh.music.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;

/**
 * 歌曲列表
 * 
 */
public class MusicList {

	public static final long shortTime = 1000 * 60;

	/**
	 * 获取手机音乐数据
	 * 
	 */
	public static List<Music> getMusicData(Context context) {
		List<Music> musicList = new ArrayList<Music>();
		ContentResolver cr = context.getContentResolver();
		if (cr != null) {
			// 获取所有歌曲
			Cursor cursor = cr.query(
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
					null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
			if (null == cursor) {
				Log.v("MusicList","MusicList: null");
				return musicList;
			}
			if (cursor.moveToFirst()) {
				do {
					Music m = new Music();
					String title = cursor.getString(cursor
							.getColumnIndex(MediaStore.Audio.Media.TITLE)); // 获取歌曲名字列表
					String singer = cursor.getString(cursor
							.getColumnIndex(MediaStore.Audio.Media.ARTIST)); // 获取歌手列表
					if ("<unknown>".equals(singer)) {
						singer = "未知艺术家"; // 歌手为空，则默认为“艺术家”
					}
					String album = cursor.getString(cursor
							.getColumnIndex(MediaStore.Audio.Media.ALBUM)); // 获取专辑列表
					long size = cursor.getLong(cursor
							.getColumnIndex(MediaStore.Audio.Media.SIZE)); // 获取歌曲文件大小
					long time = cursor.getLong(cursor
							.getColumnIndex(MediaStore.Audio.Media.DURATION)); // 获取歌曲播放时间
					String url = cursor.getString(cursor
							.getColumnIndex(MediaStore.Audio.Media.DATA)); // 获取歌曲文件的全路径
					String name = cursor
							.getString(cursor
									.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); // 歌曲文件的名称
					String sbr = name.substring(name.length() - 3,
							name.length()); // 抽取歌曲文件的的后缀名，如“.MP3 ， .wav”
					if (sbr.equals("mp3") || sbr.equals("ogg") || sbr.equals("wav")) {
						// 过滤时间较短的MP3文件。
						if (time >= shortTime) {
							// Log.v("MusicList", "MusicList :" + time);
							 Log.v("MusicList", "MusicList(Name) :" + name);
							m.setTitle(title);
							m.setSinger(singer);
							m.setAlbum(album);
							m.setSize(size);
							m.setTime(time);
							m.setUrl(url);
							m.setName(name);
							musicList.add(m);
						}
					}
				} while (cursor.moveToNext());
			}
			if (cursor != null) {
				cursor.close();
			}
		}
		return musicList;
	}

}
